<template>
  <div class="setting-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人设置</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <el-row>
        <el-col :span="15">
          <el-form ref="user" :model="user" :rules="rules" label-width="80px">
            <el-form-item label="编号">
              <span>{{ user.id }}</span>
            </el-form-item>
            <el-form-item label="手机">
              <span>{{ user.mobile }}</span>
            </el-form-item>
            <el-form-item label="媒体名称" prop="name">
              <el-input v-model="user.name"></el-input>
            </el-form-item>
            <el-form-item label="媒体介绍" prop="intro">
              <el-input type="textarea" v-model="user.intro"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="user.email"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="onSubmit" :loading="updateUserLoading">保存设置</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="4" :offset="2">
          <label for="file">
            <el-avatar
              shape="square"
              :size="150"
              fit="cover"
              :src="user.photo"
            ></el-avatar>
            <div class="avatar-tip"><p>点击修改头像</p></div>
          </label>
          <input type="file" ref="file" hidden id="file" @change="onFileChange">
        </el-col>
      </el-row>
    </el-card>
    <el-dialog
      title="修改头像"
      :visible.sync="dialogVisible"
      append-to-body
      @opened="onDialogOpened"
      @closed="onDialogClosed"
      width="20%"
      >
      <div class="preview-image-wrap">
        <img :src="previewImage" class="preview-image" ref="preview-image">
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="onUpdatePhoto" :loading="updatePhotoLoading">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getUserProfile, updateUserPhoto, updateUserProfile } from '@/api/user.js'
import globalBus from '@/utils/global-bus.js'
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
export default {
  name: 'SettingIndex',
  components: {},
  props: {},
  data () {
    return {
      user: {
        email: '',
        id: null,
        intro: '',
        mobile: '',
        name: '',
        photo: ''
      },
      dialogVisible: false,
      previewImage: '',
      cropper: null,
      updatePhotoLoading: false,
      updateUserLoading: false,
      rules: {
        name: [
          { required: true, message: '请输入媒体名称', trigger: 'change' },
          { min: 1, max: 7, message: '长度在 1 到 7 个字符', trigger: 'change' }
        ],
        intro: [
          { required: true, message: '请输入媒体介绍', trigger: 'change' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'change' },
          {
            validator: (rule, value, callback) => {
              const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
              if (mailReg.test(value)) {
                callback()
              } else {
                callback(new Error('请输入正确的邮箱格式'))
              }
            },
            trigger: 'change'
          }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created () {
    this.loadUser()
    globalBus.$emit('update-user', this.user)
  },
  mounted () {},
  methods: {
    onSubmit () {
      this.$refs.user.validate((valid) => {
        if (valid) {
          this.updateUserLoading = true
          updateUserProfile(this.user).then(res => {
            this.updateUserLoading = false
            this.$message({
              message: '更新用户信息成功',
              type: 'success'
            })
            globalBus.$emit('update-user', this.user)
          })
        } else {
          return false
        }
      })
    },
    loadUser () {
      getUserProfile().then(res => {
        this.user = res.data.data
      })
    },
    onFileChange () {
      const file = this.$refs.file
      this.previewImage = window.URL.createObjectURL(file.files[0])
      this.dialogVisible = true
      this.$refs.file.value = ''
    },
    onDialogOpened () {
      const image = this.$refs['preview-image']
      this.cropper = new Cropper(image, {
        viewMode: 1,
        dragMode: 'none',
        aspectRatio: 1,
        cropBoxResizable: false,
        background: false,
        movable: true
      })
    },
    onDialogClosed () {
      this.cropper.destroy()
    },
    onUpdatePhoto () {
      this.updatePhotoLoading = true
      this.cropper.getCroppedCanvas().toBlob((blob) => {
        const formData = new FormData()
        formData.append('photo', blob)
        updateUserPhoto(formData).then(res => {
          this.updatePhotoLoading = false
          this.dialogVisible = false
          this.user.photo = window.URL.createObjectURL(blob)
          globalBus.$emit('update-user', this.user)
          this.$message({
            message: '更新头像成功',
            type: 'success'
          })
        })
      })
    }
  }
}

</script>
<style lang='less' scoped>
.avatar-tip {
  width: 156px;
  display: flex;
  justify-content: center;
  font-size: 14px;
}
.preview-image-wrap {
  .preview-image {
    display: block;
    max-width: 100%;
    height: 200px;
  }
}
</style>
